
package com.schedualnew.mq.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class EncoderUtil
{
    public static String convertStringToUTF8(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        try {
            for (int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                if (c >= '\0' && c <= 255) {
                    sb.append(c);
                }
                else {
                    byte[] b = Character.toString(c).getBytes(StandardCharsets.UTF_8);
                    for (int value : b) {
                        int k = value;
                        k = ((k < 0) ? (k + 256) : k);
                        sb.append(Integer.toHexString(k).toUpperCase());
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    public static String barcode(String contents, int width, int height) {
        int codeWidth = 95;
        codeWidth = Math.max(codeWidth, width);
        String binary = null;
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, codeWidth, height, (Map)null);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "png", (OutputStream)os);
            byte[] bytes = os.toByteArray();
            binary = new BASE64Encoder().encode(bytes).trim();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return binary;
    }
}
